weiXinController.controller('slrOrderEditCtl',['$scope','$state','$stateParams','$timeout','$interval','$compile','$rootScope',function($scope,$state,$stateParams,$timeout,$interval,$compile,$rootScope) {

    //id
    var param = EdeyeAdmin.unzip($stateParams.param);
    $scope.id = param.id;
    console.info(param.id);

    EdeyeAdmin.post({
        url:'/orderInfo/getOrderRecordById',
        data:{
            id:param.id,
            status:'INPUT'
        }
    },{
        SUCCESS:function(ret){
            console.info(ret);
            var order = ret.order;
            $scope.warehouse_info_id = order.warehouse_info_id;
            $scope.warehouse_show = order.name;
            $scope.type = order.type;
            $scope.approval_type = order.approval_type;
            $scope.materiel_account_type = order.type_account;
            var listName = 'materiel_' + $scope.materiel_account_type.toLowerCase() + '_' + $scope.materiel_type.toLowerCase() + '_list';
            $scope[listName] = ret.data;
            $scope.$apply();
        }
    });

    // 测试$scope.$apply使用
    $scope.title = '修改申领单';

    $scope.materiel_type = 'IN';

    // 显示账外/账内备件 => OUT/IN
    $scope.materiel_account_type = 'OUT';

    // 审批方式 => COMMON/URGENT
    $scope.approval_type = 'COMMON';

    //类型 => OUT/BORROW
    $scope.type = 'OUT';

    // 账外冲销备件列表
    $scope.materiel_out_in_list = [];

    // 账内冲销备件列表
    $scope.materiel_in_in_list = [];

    //仓库id
	$scope.warehouse_info_id;

	//
    $scope.warehouse_show;

    // 相关说明
    $scope.showDes = function(){
        layer.open({
            type: 1,
            skin: 'layui-layer-rim',
            area: ['420px', '240px'],
            title: '说明',
            content: `
				<div class="row" style="margin-left: 0px; margin-right: 0px; background-color: white;">
					<div class="col-sm-12 mt-3 mb-3">
						申领单没有冲销类型的借出申领单:<br />
						实际数量<系统记录数量<br /><br />
						冲销会在后台解绑相关硬件<br />
					</div>
				</div>
				`
        });
    }



    // 切换账外账内显示
    $('#type_account').on('change',function(){
        var type_account_new = $('#type_account').val();
        $scope.$apply(function(){
            $scope.materiel_account_type = type_account_new;
        });
    });

    // 准备添加的备件绑定信息(modal中展示)
    $scope.bind_info = {
        sp_code:'',
        batch_code:'',
        type:'',
        unit:'',
        num:0,
    }

    // 弹出入库单备件新增modal
    $scope.addStoreMaterielModal = function(){
        if(!$scope.warehouse_info_id){
            EdeyeAdmin.closeMsg('请选择仓库',true,1);
            return;
        }
        $('#addStoreMaterielModal').modal({backdrop: 'static', keyboard: false});
    }

    // 关闭入库单新增modal
    $scope.closeStoreMaterielModal = function(){
        $scope.bind_info = {
            sp_code:'',
            batch_code:'',
            type:'',
            unit:'',
            num:0,
        }
        $('#addStoreMaterielModal').modal('hide');
    }

    // sp 数据获取
    $scope.spPageSearch = function(currentPage,pageSize){
        EdeyeAdmin.setDataTableDataPhone(spPageParam, {data:[]});
        var postData = {materiel_account_type:$scope.materiel_account_type, warehouse_info_id:$scope.warehouse_info_id};
        postData.currentPage = (currentPage === undefined ? 1 : currentPage);
        postData.pageSize = (pageSize === undefined ? EdeyeAdmin.getPageSizePhone(spPageParam.id) : pageSize);
        EdeyeAdmin.post({
            url:'/orderInfo/getAllMaterielGt0PageByWarehouseId',
            data:postData
        },{
            SUCCESS:function(ret){
                if(ret.code === '200'){
                    $scope.prefix = ret.prefix;
                    EdeyeAdmin.setDataTableDataPhone(spPageParam, ret.data);
                }
            }
        });
    }

    // SP号分页初始化条件
    var spPageParam = {
        id : 'spTable',
        checkbox:false,
        column : [
			{
				type:'rowNum',
				title:'编号',
			},{
				type:'key',
				mapping:'id',
				show:false
			},{
				mapping:'name',
				title:'名称',
				show:false
			},{
				mapping:'unit',
				title:'单位',
				show:false
			},{
				mapping:'sp_code',
				title:'CP编号'
			},{
				mapping:'type',
				title:'分类类型',
				trans : function(data){
					if(data.type == 'WEIGHT') {
						return "称重";
					} else if(data.type == 'QR') {
						return "二维码";
					}
					return data.type;
				}
			},{
				mapping:'borrow',
				title:'能否借用',
                trans:function(data){
                	if(data.borrow === 'CAN'){
                		return '可以借用';
                	}
                	if(data.borrow === 'CANT'){
                		return '不可借用';
                	}
                }
			},{
                type: 'function',
                title: '操作',
                titleDivStyle: 'text-align: center',
                dataDivStyle: 'text-align: center',
                func: [{
                    title: '选择',
                    css: 'btn-sm btn-outline-info',
                    text111: '<i class="fas fa-check"></i>',
                    text: '选择',
                    func: function (data) {
                        $scope.callBackSelectSpModal(data);
                    }
                }]
            }
		],
		pageConfig:{
			showGoNum:false
		},
        pageSize:[[5],10,50,100],
        page:function(cmd, currentPage, pageSize, totalPageNum){
            if('first' === cmd){
                currentPage = 1;
            }else if('prev' === cmd){
                currentPage--;
            }else if('next' === cmd){
                currentPage++;
            }else if('last' === cmd){
                currentPage = totalPageNum;
            }else if('change' === cmd){
                currentPage = 1;
            }
            $scope.spPageSearch(currentPage,pageSize);
        }
    };
    EdeyeAdmin.initDataTablePhone(spPageParam, {data:[]});

    // 弹出SP号的modal
    $scope.openSelectSpModal = function(){
        $scope.spPageSearch();
        $('#selectSpModal').modal('show');
    }

    // 选择SP号后数据回填,并关闭modal
    $scope.callBackSelectSpModal = function(data){
        // TODO 二次确认 注释 4月8日
        // layer.confirm('更换SP号后将会重新绑定', {
        //     btn: ['更换','不更换']
        // }, function(){
            $scope.$apply(function(){
                $scope.bind_info.sp_code = data.sp_code;
                $scope.bind_info.type = data.type;
                if($scope.bind_info.type === 'WEIGHT'){
                    $scope.bind_info.type_view = '称重';
                }
                if($scope.bind_info.type === 'QR'){
                    $scope.bind_info.type_view = '二维码';
                }
                if($scope.bind_info.type === 'RFID'){
                    $scope.bind_info.type_view = data.type;
                }
                if($scope.materiel_type === 'IN'){

                }

                $scope.bind_info.batch_code = '';
                $scope.bind_info.unit = data.unit;
            });
            layer.closeAll();
        // }, function(){
        // });
        EdeyeAdmin.setDataTableDataPhone(spPageParam, {data:[]});
        $('#selectSpModal').modal('hide');
    }


    // 批次号分页初始化条件
    var batchPageParam = {
        id : 'batchTable',
        checkbox:false,
        column : [
            {
                type:'rowNum',
                title:'编号',
            },{
                type:'key',
                mapping:'id',
                show:false
            },{
                mapping:'batch_code',
                title:'批次号'
            },{
                type: 'function',
                title: '操作',
                titleDivStyle: 'text-align: center',
                dataDivStyle: 'text-align: center',
                func: [{
                    title: '选择',
                    css: 'btn-sm btn-outline-info',
                    text111: '<i class="fas fa-check"></i>',
                    text: '选择',
                    func: function (data) {
                        $scope.callBackSelectBatchModal(data);
                    }
                }]
            }
        ],
		pageConfig:{
			showGoNum:false
		},
        pageSize:[[5],10,50,100],
        page:function(cmd, currentPage, pageSize, totalPageNum){
            if('first' === cmd){
                currentPage = 1;
            }else if('prev' === cmd){
                currentPage--;
            }else if('next' === cmd){
                currentPage++;
            }else if('last' === cmd){
                currentPage = totalPageNum;
            }else if('change' === cmd){
                currentPage = 1;
            }
            $scope.batchPageSearch(currentPage,pageSize);
        }
    };
    EdeyeAdmin.initDataTablePhone(batchPageParam, {data:[]});

    $scope.batchPageSearch = function(currentPage,pageSize){
        EdeyeAdmin.setDataTableDataPhone(batchPageParam, {data:[]});
        var postData = {materiel_account_type:$scope.materiel_account_type,sp_code:$scope.bind_info.sp_code,warehouse_info_id:$scope.warehouse_info_id};
        postData.currentPage = (currentPage === undefined ? 1 : currentPage);
        postData.pageSize = (pageSize === undefined ? EdeyeAdmin.getPageSizePhone(batchPageParam.id) : pageSize);
        EdeyeAdmin.post({
            url:'/orderInfo/getAllMaterielTypeStockGt0PageByWarehouseId',
            data:postData
        },{
            SUCCESS:function(ret){
                if(ret.code === '200'){
                    $scope.prefix = ret.prefix;
                    EdeyeAdmin.setDataTableDataPhone(batchPageParam, ret.data);
                }
            }
        });
    }

    // 弹出批次号号的modal
    $scope.openSelectBatchModal = function(){
        if($scope.bind_info.sp_code.length < 1){
            EdeyeAdmin.closeMsg('请先选择CP号',true,1);
            return;
        }
        $scope.batchPageSearch();
        $('#selectBatchModal').modal('show');
    }

    // 选择批次号号后数据回填,并关闭modal
    $scope.callBackSelectBatchModal = function(data){
        $scope.$apply(function(){
            $scope.bind_info.batch_code = data.batch_code;
        });
        EdeyeAdmin.setDataTableDataPhone(batchPageParam, {data:[]});
        $('#selectBatchModal').modal('hide');
    }

    // 多层modal必须使用这个方法,否则会造成上1层的modal失去滚动条
    $('#selectSpModal,#selectBatchModal,#selectShelfModal,#selectRfidModal,#selectBasketModal').on('hidden.bs.modal', function (event) {
        $("body").addClass("modal-open");
    });


    // 新增入库单备件并关闭modal
    $scope.addStoreMateriel = function(){
        // 实际/冲销校验SP号,批次号,新增数量
        var ret = EdeyeAdmin.checkKit.finalCheck($scope.bind_info, true, {
            'sp_code': {
                method: 'strRange',
                methodParam: ['&&', ['>=', 1], ['<=', 128]],
                msg: '请选择CP号'
            },
            'batch_code': {
                method: 'strRange',
                methodParam: ['&&', ['>=', 1], ['<=', 128]],
                msg: '请选择批次号'
            },
            'num': {
                method: 'integerRange',
                methodParam: ['&&', ['>=', 1], ['<=', 1000000]],
                msg: '申领数量在1~1000000'
            }
        });
        if (!ret.flag) {
            EdeyeAdmin.closeMsg(ret.msg.join('<br />'), false, 1);
            return;
        }

        var listName = 'materiel_' + $scope.materiel_account_type.toLowerCase() + '_' + $scope.materiel_type.toLowerCase() + '_list';
        $scope[listName].push({
            id:moment().format('YYMMDDHHmmssSSS'),
            sp_code:$scope.bind_info.sp_code,
            batch_code:$scope.bind_info.batch_code,
            type:$scope.bind_info.type,
            num:$scope.bind_info.num,
            unit:$scope.bind_info.unit,
            type_name:($scope.bind_info.type === 'WEIGHT' ? '称重' : ($scope.bind_info.type === 'QR' ? '二维码' : $scope.bind_info.type)),
        });

        console.info()
        $scope.closeStoreMaterielModal();
    }

    // 已加入到入库单中的备件查看时的ng1对象
    $scope.materielViewObj = {};



    // 提交入库单
    $scope.submitStore = function(){
    	if(!$scope.warehouse_info_id){
            EdeyeAdmin.closeMsg('请选择仓库',true,1);
            return;
		}
        var listName = 'materiel_' + $scope.materiel_account_type.toLowerCase() + '_' + $scope.materiel_type.toLowerCase() + '_list';
        if($scope[listName].length < 1){
            EdeyeAdmin.closeMsg('请添加备件',true,1);
            return;
        }
        // TODO 二次确认 注释 4月8日
        // layer.confirm('是否提交申领单?', {
        //     btn: ['确认','取消'],
        //     closeBtn: false
        // }, function(){
            EdeyeAdmin.post({
                url: '/orderInfo/updateNewOrder',
                data: {
                    id:$scope.id,
                    param:$scope[listName]
                }
            }, {
                SUCCESS: function (ret) {
                    EdeyeAdmin.closeMsg(ret.msg,true,1);
                }
            });
            layer.closeAll();
        // });
    }

    // 移出加入到入库单中的备件
    $scope.removeStoreMateriel = function(id){
        // TODO 二次确认 注释 4月8日
        // layer.confirm('是否将备件从列表中移出?', {
        //         btn: ['确认','取消'],
        //         closeBtn: false
        //     }, function(){
                var listName = 'materiel_' + $scope.materiel_account_type.toLowerCase() + '_' + $scope.materiel_type.toLowerCase() + '_list';
                for(var tmpKey in $scope[listName]){
                    if($scope[listName][tmpKey].id === id){
                        // $scope.$apply(function(){
                            $scope[listName].splice(tmpKey, 1);
                        // });
                        break;
                    }
                }
                layer.closeAll();
        //     }, function(){
        //     }
        // );
    }

    // 查看加入到入库单中的备件详情
    $scope.viewStoreMateriel = function(id){
        var listName = 'materiel_' + $scope.materiel_account_type.toLowerCase() + '_' + $scope.materiel_type.toLowerCase() + '_list';
        for(var tmpKey in $scope[listName]){
            if($scope[listName][tmpKey].id === id){
                $scope.materielViewObj = $scope[listName][tmpKey];
                break;
            }
        }
        $('#viewMaterielModal').modal('show');
    }
}]);